<?php
// +----------------------------------------------------------------------
// | quanli team
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.fistforward.com/ All rights reserved.
// +----------------------------------------------------------------------
// | add by allen.qiang 20150429 TEA-FUN-1003-TEA-下午茶会员导入功能
// +----------------------------------------------------------------------


/**
 * 会员操作功能
 * @package  htdocs
 * @subpackage  quanliadmin
 * add by allen.qiang 20150429 TEA-FUN-1003-TEA-下午茶会员导入功能
 */

quanli_require('module/base/customer/quanliCustTea.class.php');
quanli_require('module/base/system/itemHandler.class.php');
quanli_require('module/base/customer/quanliCust.class.php');

class pa_customerTea{
	
	public function execute() {
		
		if (isset($_REQUEST['operFlg']) && quanli_is_int($_REQUEST['operFlg'])) {

			switch ( $_REQUEST['operFlg'] ) {

				case 1: //会员查询
					$this->custList();
					break;
                case 2: //批量导入会员
                    $this->importCustTea();
                    break;
                case 3: //add by allen.qiang 20150527 批量更新会员权益
                    $this->importUpdateRights();
                    break;
                default:
                    backendError();
                    break;
			}

		} else {
            backendError();

        }
	}
	/**
	 * 会员初始化查询
	 */
	private function custList() {

		global $G_PGLOB;

		$G_PGLOB->smarty->display('customer/customerTea.tpl');

	}

    /**
     * //add by allen.qiang 20150527 批量更新会员权益
     */
    private function importUpdateRights() {

        global $G_PGLOB;
        quanli_include('module/base/common/quanliFile.class.php');

        //检查上传的文件
        switch ($_FILES['search_file_UpdateRights']['error']) {

            case 1:
                // 文件大小超出了服务器的空间大小
                echo "<script>parent.E.loadding.close();parent.E.alert('文件过大，请重新上传');</script>";
                return;
                break;

            case 2:
                // 要上传的文件大小超出浏览器限制
                echo "<script>parent.E.loadding.close();parent.E.alert('文件过大，请重新上传');</script>";
                return;
                break;

            case 3:
                // 文件仅部分被上传
                echo "<script>parent.E.loadding.close();parent.E.alert('文件上传有误，请重新上传');</script>";
                return;
                break;

            case 4:
                // 没有找到要上传的文件
                echo "<script>parent.E.loadding.close();parent.E.alert('请选择上传的文件');</script>";
                return;
                break;

            case 5:
                // 服务器临时文件夹丢失
                echo "<script>parent.E.loadding.close();parent.E.alert('系统错误，上传失败');</script>";
                return;
                break;

            case 6:
                // 文件写入到临时文件夹出错
                echo "<script>parent.E.loadding.close();parent.E.alert('系统错误，上传失败');</script>";
                return;
                break;
        }

        //上传路径
        $upload_path = 'quanliadmin/docroot/file/customer/';

        //分解文件名和扩展名
        $fileArray = explode('.', $_FILES['search_file_UpdateRights']['name']);
        $index = count($fileArray) - 1;

        //将扩展名转化成小写
        $extension = strtolower($fileArray[$index]);


        //检查格式是否正确
        if ($extension != 'xlsx' && $extension != 'csv' && $extension != 'xls' ) {
            echo "<script>parent.E.loadding.close();parent.E.alert('文件格式有误');</script>";
            return;
        }

        //检查文件夹
        if (!file_exists(G_APPLICATION_BASEPATH . $upload_path)) {
            mkdir(G_APPLICATION_BASEPATH . $upload_path, 0777, true);
        }

        //获取UUID
        $guid = make_uuid();

        //文件名
        $moveFile = $upload_path . $guid . '.' . $extension;

        if (!move_uploaded_file($_FILES['search_file_UpdateRights']['tmp_name'], G_APPLICATION_BASEPATH . $moveFile)) {
            echo "<script>parent.E.loadding.close();parent.E.alert('系统错误，上传失败');</script>";
            return;
        }

        //读取文件
        $excelData = file(G_APPLICATION_BASEPATH . $moveFile);
        if (!isset($excelData[0])) {
            echo "<script>parent.E.loadding.close();parent.E.alert('导入数据为空');</script>";
            return;
        }

        quanli_include('module/base/common/quanliFile.class.php');

        //实例文件
        $quanliFile = new quanliFile;
        /**
         * 读取Excel文件内容
         */
        $data_array = $quanliFile->readerExcel1(G_APPLICATION_BASEPATH . $moveFile,2 );

        if ($data_array['code'] != 200) {
            die('<script>parent.customer.importUpdateRightsMsg("导入过程异常，请重试", 0);</script>');
        }

        //取得待发数据总数量
        $data_cnt=count($data_array['data']);

        if ($data_cnt ==1 && !isset($data_array['data'][0][0])) {
            die('<script>parent.customer.importUpdateRightsMsg("文件无数据", 0);</script>');
        }

        $ret_message = "本次处理总数：".$data_cnt."<br />";
        //循环处理
        foreach($data_array['data'] as &$customer) {
            try{
                $G_PGLOB->DBCA->beginTransaction();

                $dunch_cust_master = new entity('dunch_cust_master');
                $dunch_cust_master->custID = $customer[0];

                //查询会员数据
                if (!$G_PGLOB->DBCA->fetch($dunch_cust_master))
                {
                    $ret_message = $ret_message . $customer[0] . '-->信息没有找到<br />';
                    $G_PGLOB->DBCA->rollBack();
                    continue;
                }
                //多杯
                if(isset($customer[1]))
                    $dunch_cust_master->is_right=$customer[1];
                //请客权益
                if(isset($customer[2]))
                    $dunch_cust_master->is_treat=$customer[2];
                //撒娇权益
                if(isset($customer[3]))
                    $dunch_cust_master->is_coquetry=$customer[3];
                if (!$G_PGLOB->DBCA->save($dunch_cust_master)) {
                    $ret_message = $ret_message . $customer[0] . '-->更新失败<br />';
                    $G_PGLOB->DBCA->rollBack();
                    continue;
                }

                $G_PGLOB->DBCA->commit();
            }catch (Exception $e) {
                error_log(print_r($e,1));
                $ret_message = $ret_message . $customer[0] . '-->更新失败<br />';
                $G_PGLOB->DBCA->rollBack();
            }
        }
        $ret_message = $ret_message . '更新完成<br />';
        die('<script>parent.customer.importUpdateRightsMsg("'.$ret_message.'", 0);</script>');


    }

    /**
     * 导入批量会员
     */
    private function importCustTea() {
        global $G_PGLOB;
        $currentOperator = $G_PGLOB->currentUserID;                         //当前操作者
        $password_Default ='teamcake';                                      //默认密码

        quanli_include('module/base/common/quanliFile.class.php');

        //实例文件
        $quanliFile = new quanliFile;

        /**
         * 得到上传文件，并保存为新文件在服务器上
         */
        $upload_result_array = $quanliFile->get_upload_file( 'customer' );

        if ($upload_result_array['code'] != 200) {
            die('<script>parent.customer.importMsg("' . $upload_result_array['message'] . '", 0);</script>');
        }
        /**
         * 读取Excel文件内容
         */
        //判断本次导入数据总数
        $data_array = $quanliFile->readerExcel1( $upload_result_array['data'],1 );
        if ($data_array['code'] != 200) {
            die('<script>parent.customer.importMsg("导入过程异常，请重试", 0);</script>');
        }
        //取得待发数据总数量
        $data_cnt=count($data_array['data']);
        if($data_cnt==1)
            die('<script>parent.customer.importMsg("导入数据不能为空", 0);</script>');


        $data_array = $quanliFile->readerExcel1( $upload_result_array['data'],2 );

        if ($data_array['code'] != 200) {
            die('<script>parent.customer.importMsg("导入过程异常，请重试", 0);</script>');
        }

        //取得待发数据总数量
        $data_cnt=count($data_array['data']);

        if ($data_cnt ==1 && !isset($data_array['data'][0][0])) {
            die('<script>parent.customer.importMsg("文件无数据", 0);</script>');
        }

        $ret_message = "本次处理总数：".$data_cnt."<br />";
        //循环处理
        foreach($data_array['data'] as &$customer) {
            try{
                $G_PGLOB->DBCA->beginTransaction();
                //实例会员类(Mcake)
                $quanliCust = new quanliCust();
                //前台注册会员信息
                $args_array = array(
                    'custID' => $customer[0],       //手机号
                    'custname' => $customer[1],     //姓名
                    'pwd' => $password_Default,     //默认密码
                    'pwd2' => $password_Default,    //默认密码
                    'sexy' => 0,                    //不详
                    'custSource' => 7,              //线下
                    'custType' => 1,                //普通会员操作者
                    'editor' => $currentOperator    //普通会员
                );
                $result_array = $quanliCust->register( $args_array );
                if ($result_array['code'] != 200) {
                    if($result_array['message']=='会员名已被使用，请使用其他会员名尝试注册')
                    {
                        $ret_message = $ret_message . $customer[0] . '-->Mcake已经是会员<br />';
                        $args_array = array(
                            'custID' => $customer[0]       //手机号
                        );
                        $result_array = $quanliCust->searchCustomerInfo( $args_array );
                        $ret_pcustID = $result_array[0]['pcustID'];//取得已有MCAKE会员号
                    }else
                    {
                        //mcake 注册失败
                        $ret_message = $ret_message . $customer[0] . '-->Mcake会员导入失败  '.$result_array['message'].'<br />';
                        $G_PGLOB->DBCA->rollBack();
                        continue;
                    }

                }else
                {
                    $ret_pcustID = $result_array['data']['pcustID'];//取得本次注册会员号
                }

                //判断数据是否已存在
                $dunch_cust_master_obj = new entity('dunch_cust_master');
                $dunch_cust_master_obj->custID = $customer[0];
                if (!$G_PGLOB->DBCA->fetch($dunch_cust_master_obj)) {
                    //注册下午茶会员
                    $dunch_cust_master_obj = new entity('dunch_cust_master');
                    $dunch_cust_master_obj->creator = $currentOperator;
                    $dunch_cust_master_obj->custID = $customer[0];
                    $dunch_cust_master_obj->pcustID = $ret_pcustID;
                    $dunch_cust_master_obj->brandID =1;
                    $dunch_cust_master_obj->is_right =1;                    //下午茶权益
                    $dunch_cust_master_obj->is_coquetry =1;                 //撒娇权益
                    if (!$G_PGLOB->DBCA->save($dunch_cust_master_obj)) {
                        $ret_message = $ret_message . $customer[0] . '-->下午茶会员导入失败<br />';
                        $G_PGLOB->DBCA->rollBack();
                        continue;
                    }
                }else{
                    $ret_message = $ret_message . $customer[0] . '-->已是下午茶会员<br />';
                    $G_PGLOB->DBCA->rollBack();
                    continue;
                }

                $G_PGLOB->DBCA->commit();
            }catch (Exception $e) {
                error_log(print_r($e,1));
                $ret_message = $ret_message . $customer[0] . '-->导入失败<br />';
                $G_PGLOB->DBCA->rollBack();
            }
        }
        $ret_message = $ret_message . '导入完成<br />';
        die('<script>parent.customer.importMsg("'.$ret_message.'", 0);</script>');
    }

}